<template>
  <div class="">
    <div class="header">
      <input
        @focus="isShow = true"
        @keydown.down="down"
        @keydown.up="up"
        @blur="searchChange"
        @keydown.enter="ok"
        v-model="searchValue"
        type="text"
      />
    </div>

    <div v-if="isShow">
      <div class="top">
        <li>历史记录</li>
        <li style="color:red;" @click="$store.commit('removeAll')">全部删除</li>
      </div>
      <div class="hitory">
        <p
          @click="historySearch(v, i)"
          v-for="(v, i) in $store.state.objList"
          :key="i"
          :class="{ active: downIndex == i }"
        >
          <span>{{ v }}</span
          ><span @click.stop="$store.commit('remove', i)">X</span>
        </p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, defineEmits } from "vue";
import { useStore } from "vuex";
import axios from "axios";
let searchValue = ref("");
let obj = ref([]);
let store = useStore();
let topIndex = ref(-1);
let app = ref([]);
let isShow = ref(false);
let emit = defineEmits(["searchChange"]);

let downIndex = ref(-1);

function searchChange() {
  emit("searchChange", searchValue.value);
}

// 向下的函数
function down() {
  downIndex.value++;
  if (downIndex.value > store.state.objList.length - 1) {
    downIndex.value = 0;
  }
  console.log(downIndex.value);
  // 获取数组的index值传给 input 框
  searchValue.value = store.state.objList[downIndex.value];
  searchChange()
}
// 想上的函数
function up() {
  downIndex.value--;
  if (downIndex.value < 0) {
    downIndex.value = store.state.objList.length - 1;
  }
  // 获取数组的index值传给 input 框
  searchValue.value = store.state.objList[downIndex.value];
  searchChange()
}

function ok() {
  emit("searchChange", searchValue.value);
  isShow.value = false;
}

function historySearch(item, i) {
  searchValue.value = item;
  console.log(i);
  downIndex.value = i;
  searchChange();
}
</script>

<style lang="scss" scoped>
.header {
  width: 100%;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: red;

  input {
    width: 80%;
    height: 35px;
    background-color: #fff;
    border-radius: 25px;
    border: 0;
    padding-left: 10px;
  }
}
.active {
  background-color: pink;
}
p {
  border: 1px solid #000;
  padding: 10px 20px;
  margin: 5px;
  height: 20px;
  width: 100%;
  position: relative;
  span {
    &:nth-of-type(2) {
      position: absolute;
      right: 92px;
    }
  }
}
.top {
  width: 100%;
  display: flex;
  justify-content: space-between;
  li {
    list-style: none;
    padding: 0 10px;
  }
}
.hitory {
  width: 100%;
  height: auto;

  background-color: rgb(206, 205, 205);
}
</style>
